package com.demo.youxuanmall.controller;

import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public Result<Void> register(@RequestParam String username,
                               @RequestParam String password,
                               @RequestParam(required = false) String nickname,
                               @RequestParam(required = false) String phone,
                               @RequestParam(required = false) String email,
                               @RequestParam(required = false, defaultValue = "1") Integer gender,
                               @RequestParam(required = false, defaultValue = "0") Integer role) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setNickname(nickname);
            user.setPhone(phone);
            user.setEmail(email);
            user.setGender(gender);
            user.setRole(role);
            
            userService.register(user);
            return Result.success();
        } catch (Exception e) {
            logger.error("注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request) {
        // 清除session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "success";
    }

    /**
     * 我的订单页面
     */
    @GetMapping("/orders")
    public String orders() {
        return "redirect:/order/list";
    }
}